// pages/excel/index.js

const XLSX = require('../../libs/xlsx.mini.min.js');
const FIELD_MAPPING = {
    content: ['扫码内容', 'content'],
    time: ['扫码时间', 'time']
  };
Page({
    scancode() {
                wx.authorize({
                  scope: 'scope.camera', 
                  success: () => {
                    wx.scanCode({
                      success: (res) => {
                        const{scanList}=this.data;
                        const currentContent=res.result;
                        const isrepeat=scanList.some(item=>item.content===currentContent);
                        if(isrepeat){
                            this.setData({
                                repeatCount:this.data.repeatCount+1
                            });
                            wx.showToast({
                              title: '重复扫码,已过滤',
                              icon:'none'
                            });
                            return;
                        }
                        const currentTime=new Date().toLocaleString(
                            'zh-CN',{
                                year:'numeric',
                                month:'2-digit',
                                day:'2-digit',
                                hour:'2-digit',
                                minute:'2-digit',
                                second:'2-digit'
                            }).replace(',','-');
                        const newindex = this.data.scanindex + 1;
                        const newrecord = {
                          index: newindex,
                          content: res.result,
                          time:currentTime
                        };
                        this.setData({
                          scanindex: newindex,
                          scanList: [...this.data.scanList, newrecord]
                        });
                        wx.setStorageSync('scanHistory', this.data.scanList);
                        wx.showToast({ title: '扫描成功' });
                      },
                      fail: (err) => {
                        console.error('扫码失败', err);
                        wx.showToast({ title: '扫码失败', icon: 'none' });
                      }
                    });
                  },
                  fail: (err) => {
                    
                    wx.showModal({
                      title: '需要摄像头权限',
                      content: '小程序需要摄像头权限才能扫码，请前往设置开启',
                      success: (res) => {
                        if (res.confirm) {
                          wx.openSetting({
                            success: (settingRes) => {
             if (settingRes.authSetting['scope.camera']) {
                                        this.scancode(); 
                                      }
                                    }
                                  });
                                }
                              }
                            });
                          }
                        });
                      },
                  /**
                   * 页面的初始数据
                   */
                  data: {
                scanList: [],
                scanindex: 0,
                repeatCount: 0
                  },
                  reset(){
                    this.setData({
                        scanList:[],
                        scanindex:0,
                        repeatCount:0
                    });
                    wx.showToast({
                        title:'已重置记录',
                        icon:"none"
                    });
                },
                
  exportExcel() {
    const { scanList } = this.data;
    if (scanList.length === 0) {
      wx.showToast({ title: '暂无扫码记录', icon: 'none' });
      return;
    }

    const excelData = scanList.map(item => ({
      '序号': item.index,
      '扫码内容': item.content,
      ' ': ' ',
      '扫码时间': item.time
    }));
    
    const worksheet = XLSX.utils.json_to_sheet(excelData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '扫码记录');
    worksheet['!cols']=[,{wch:30}];
    
    const fileData = XLSX.write(workbook, { bookType: 'xlsx', type: 'base64' });
    
    this.saveExcelFile(fileData);
  },

  /**
   
   * @param {string} base64Data Excel文件base64数据
   */
  saveExcelFile(base64Data) {
    const fs = wx.getFileSystemManager();
    const filePath = `${wx.env.USER_DATA_PATH}/扫码记录.xlsx`;
  
    // 1. 先写入临时文件
    fs.writeFile({
      filePath: filePath,
      data: base64Data,
      encoding: 'base64',
      success: () => {
        // 2. 调用微信的保存文件API，将临时文件保存到手机
        wx.saveFileToDisk({
          filePath: filePath,
          success: () => {
            wx.showToast({ title: '文件已保存到手机', icon: 'none' });
          },
          fail: (err) => {
            console.error('保存到手机失败', err);
            // 兼容旧版本微信（基础库 < 2.18.0）
            if (err.errMsg.includes('saveFileToDisk:fail')) {
              wx.showModal({
                title: '保存提示',
                content: '请通过"转发"将文件保存到微信文件传输助手',
                confirmText: '去转发',
                success: (res) => {
                  if (res.confirm) {
                    wx.shareFileMessage({
                      filePath: filePath,
                      fileName: '扫码记录.xlsx'
                    });
                  }
                }
              });
            }
          }
        });
      },
      fail: (err) => {
        console.error('写入临时文件失败', err);
        wx.showToast({ title: '生成文件失败', icon: 'none' });
      }
    });
  },
// 在页面的js文件顶部引入


// 字段映射配置


importExcel() {
  wx.chooseMessageFile({
    count: 1,
    type: 'file',
    fileType: ['xlsx'],
    success: (res) => {
      if (res.tempFiles.length === 0) {
        wx.showToast({ title: '未选择文件', icon: 'none' });
        return;
      }
      this.readExcelFile(res.tempFiles[0]);
    },
    fail: (err) => {
      wx.showToast({ title: '选择文件失败', icon: 'none' });
      console.error('选择文件失败', err);
    }
  });
},

readExcelFile(file) {
  const fs = wx.getFileSystemManager();
  fs.readFile({
    filePath: file.path,
    encoding: 'binary',
    success: (res) => {
      try {
        const workbook = XLSX.read(res.data, { type: 'binary' });
        if (workbook.SheetNames.length === 0) {
          wx.showToast({ title: 'Excel无工作表', icon: 'none' });
          return;
        }
        
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const excelData = XLSX.utils.sheet_to_json(worksheet);
        this.mergeData(excelData);
      } catch (e) {
        wx.showToast({ title: '解析Excel失败', icon: 'none' });
        console.error('解析Excel失败', e);
      }
    },
    fail: (err) => {
      wx.showToast({ title: '读取文件失败', icon: 'none' });
      console.error('读取文件失败', err);
    }
  });
},

mergeData(excelData) {
  if (!Array.isArray(excelData) || excelData.length === 0) {
    wx.showToast({ title: '无有效数据', icon: 'none' });
    return;
  }

  const newScanList = [...this.data.scanList];
  let maxIndex = this.data.scanindex;

  excelData.forEach((item) => {
    // 动态获取字段值
    const getFieldValue = (field) => {
      const possibleKeys = FIELD_MAPPING[field];
      for (const key of possibleKeys) {
        if (item[key] !== undefined) return item[key];
      }
      return '';
    };

    const newItem = {
      index: ++maxIndex,
      content: getFieldValue('content'),
      time: getFieldValue('time') || new Date().toLocaleString()
    };
    
    newScanList.push(newItem);
  });

  this.setData({
    scanList: newScanList,
    scanindex: maxIndex
  });
  
  wx.setStorageSync('scanHistory', newScanList);
  wx.showToast({ title: `成功导入${excelData.length}条数据` });
},
  
      // 扫码功能（原逻辑保留）
     
    
      // 页面加载时恢复缓存
      

  
  /**
   * 页面的初始数据
   */
 

  /**
   * 生命周期函数--监听页面加载
   */
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})